package com.kun.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendOrderMessage(Integer id,String message){

        String exchangeName = "order_exchange";
        String routingKey = "";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,id+":"+message);
        System.out.println(exchangeName+"：发送消息成功！");

    }

    public void sendOrderMessage_direct(Integer id,String message){

        String exchangeName = "order_direct_exchange";
        String routingKey = "email";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,id+":"+message);
        System.out.println(exchangeName+"：发送消息成功！");

    }

    public void sendOrderMessage_topic(Integer id,String message){

        String exchangeName = "order_topic_exchange";
        String routingKey = "com.email.order";//*：一个，#：任意多个
        rabbitTemplate.convertAndSend(exchangeName,routingKey,id+":"+message);
        System.out.println(exchangeName+"：发送消息成功！");

    }


    public void sendOrderMessage_ttl_direct(Integer id,String message){

        String exchangeName = "ttl_direct_exchange";
        String routingKey = "ttl_queue_direct";//*：一个，#：任意多个
        rabbitTemplate.convertAndSend(exchangeName,routingKey,id+":"+message);
        System.out.println(exchangeName+"：发送消息成功！");

    }
    public void sendOrderMessage_ttl_message_direct(Integer id,String message){

        String exchangeName = "ttl_direct_exchange";
        MessagePostProcessor messagePostProcessor = new MessagePostProcessor(){
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("5000");
                message.getMessageProperties().setContentEncoding("UTF-8");
                return message;
            }
        };
        String routingKey = "ttl_message_queue_direct";//*：一个，#：任意多个
        rabbitTemplate.convertAndSend(exchangeName,routingKey,id+":"+message,messagePostProcessor);
        System.out.println(exchangeName+"：发送消息成功！");

    }

    public void sendOrderMessage_dead_letter_direct_test(Integer id,String message){
        String exchangeName = "dead_letter_exchange_test";
        String routingKey = "dead_letter_queue_test";//*：一个，#：任意多个
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend(exchangeName,routingKey,id+":"+message);
        }
        System.out.println(exchangeName+"：发送消息成功！");

    }

}
